package com.daqsoft.interceptor;

import com.daqsoft.data.User;
import com.daqsoft.dto.GeneralResultEnum;
import com.daqsoft.permission.Verify;
import com.daqsoft.permission.VerifyType;
import com.daqsoft.permission.ServletStorage;
import com.daqsoft.service.system.PermissionService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 权限拦截器
 * @author 周麟东 on 9:29
 */
@Aspect
@Component
public class PermissionInterceptor {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${dev.server}")
    private boolean isDev;
    @Autowired
    private PermissionService permissionService;

    @Around("execution(* com.daqsoft.controller..*(..))")
    public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod(); //获取被拦截的方法
        if (method.getDeclaredAnnotation(Verify.class) == null){
            logger.error("请求方法[{}.{}()]被权限拦截器拦截,原因是:该方法没有声明权限类型,请在方法上增加com.daqsoft.permission.Permission注解!",method.getDeclaringClass().getName(),method.getName());
            return GeneralResultEnum.PERMISSION_DENIED;
        }
        VerifyType permissionType = method.getDeclaredAnnotation(Verify.class).value();
        //如果是调试模式 直接放行
        if (isDev && permissionType== VerifyType.HAVE_PERMISSION && haveLogin()){
            logger.debug("请求方法[{}.{}()]被直接放行 , 因为当前为调试模式",method.getDeclaringClass().getName(),method.getName());
            return pjp.proceed();
        }
        switch (permissionType){
            case EVERYONE: return pjp.proceed();
            case NEED_LOGIN: return haveLogin()?pjp.proceed():GeneralResultEnum.NEED_LOGIN;
            case HAVE_PERMISSION:
                if(!haveLogin()){
                    return  GeneralResultEnum.NEED_LOGIN;
                }
                return havePermission()?pjp.proceed():GeneralResultEnum.PERMISSION_DENIED;
        }
        return GeneralResultEnum.PERMISSION_DENIED;
    }

    /**
     * 验证用户是否登录 已经登录了返回true , 没有登录返回false
     */
    private boolean haveLogin(){
        User user = (User) ServletStorage.getSession().getAttribute("user");
        if (user == null){
//            logger.error("权限验证错误 , 用户尚未登录");
            return false;
        }
        return true;
    }

    /**
     * 验证用户是否有权限
     * @return 有返回true 没有返回false
     */
    private boolean havePermission(){
        if (!haveLogin()){
            return false;
        }
        //检查权限
        HttpServletRequest request = ServletStorage.getRequest();
        User user = (User) request.getSession().getAttribute("user");
        String path = request.getServletPath();
        return  permissionService.verifyPermission(user,path);
    }

}
